/*
 * @Author: yangrongxin
 * @Date: 2021-08-17 18:37:45
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:27:30
 */
import { useState, useEffect } from 'react';
import { View, Text, Image, Button } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import { AtIcon } from 'taro-ui';
import { placeOrder } from '@/services/global';
import { payFn } from '@/components/PayFn';
import { MEDIA_TYPE } from '@/const/dataDictionary';
import { loginWithFn } from '@/utils/common';
import { getDetail, addFavorite, getConfirmInfoFlag } from './service';
import { UserDataComfirm } from './components';
import styles from './index.module.less';
import { deleteFavorite } from '../My/compoents/MyFavorite/service';

const AssessmentDetail = () => {
  const {
    params: { measureTableId: propsMeasureTableId },
  } = useRouter();

  console.log('measureTableId', propsMeasureTableId);

  const [detailData, setDetailData] = useState<any>({});
  const [isSelected, setIsSelected] = useState<boolean>(false);
  const [showCheck, setShowCheck] = useState<boolean>(false);

  useEffect(() => {
    getDetail({
      measureTableId: propsMeasureTableId,
    }).then((res: any) => {
      if (res?.measureTableId) {
        setDetailData(res);
        setIsSelected(Boolean(res?.isFavorite));
      }
    });
  }, []);

  /* 进行微信支付 */
  const toPay = () => {
    // 进行下单下单之前判断当前的登录状态
    loginWithFn(() => {
      placeOrder({
        measureTableId: propsMeasureTableId,
      }).then((res: any) => {
        if (!res) return;
        const { orderId } = res;
        payFn(orderId, name, measureTableId, price === '0.00');
        console.log('placeOrder', res);
      });
    });
    // 直接进行下单不展示确认资料
    return;
    /*
     * 先判断当前是不是今日第一次 进行测评 如果是的话 需要确认用户信息
     * 获取订单数据之后
     * 当前是免费的状态 直接调用支付的接口
     * 当前是收费的状态 获取小程序的支付票据 进行支付 -> 支付完成之后检验支付状态
     */
    getConfirmInfoFlag().then((isFirstLogin: any) => {
      console.log('isFirstLogin', isFirstLogin);
      // 1 已经确认过 2 未确认过
      if (isFirstLogin?.confirmInfoFlag === 1) {
        setShowCheck(false);
        placeOrder({
          measureTableId: propsMeasureTableId,
        }).then((res: any) => {
          if (!res) return;
          const { orderId } = res;
          payFn(orderId, name, measureTableId, price === '0.00');
        });
      }
      // 当前未确认过 展示弹窗
      if (isFirstLogin?.confirmInfoFlag === 2) {
        setShowCheck(true);
      }
    });
  };

  /* 切换当前的收藏状态 */
  const changeFavorite = () => {
    loginWithFn(() => {
      let requestFn = addFavorite;
      let params: any = {
        objectId: propsMeasureTableId,
        type: MEDIA_TYPE.CEPING,
      };
      if (isSelected) {
        requestFn = deleteFavorite;
        params = {
          objectIds: [propsMeasureTableId],
          type: MEDIA_TYPE.CEPING,
        };
      }
      requestFn(params).then((res: any) => {
        setIsSelected(!isSelected);
        console.log('favorite', res);
      });
    });
  };

  const {
    headImg = 'https://hxgywx.oss-cn-shenzhen.aliyuncs.com/hxt-wxminiprogram/pubIcon.png',
    introduce,
    details,
    measureTableId,
    name,
    num = 0,
    price = '0.00',
    testNum = 0,
    instruction,
  } = detailData;

  /* 获取按钮的描述详情 */
  const getDesc = () => {
    let priceDesc: string = '¥9.99';
    if (price === '0.00') {
      priceDesc = '免费测试';
    } else {
      priceDesc = `${price}立即测试`;
    }
    return priceDesc;
  };

  console.log('showCheck', showCheck);

  return (
    <View className={styles.container}>
      <Image src={headImg} mode="aspectFill" />
      {/* 展示项目图片 */}
      <View className={styles.header}>
        <Text>{name}</Text>
        <View>
          <Text>{num || 0}题</Text>
          <Text>｜</Text>
          <Text>{testNum || 0}人已测</Text>
        </View>
        {/* TODO: 标签系统目前后台没有数据不进行展示 */}
        {/* <View>
          <View>
            <View>
              <Text>#</Text>
            </View>
            <Text>性格心理测试</Text>
          </View>
          <View>
            <View>
              <Text>#</Text>
            </View>
            <Text>睡眠测试</Text>
          </View>
        </View> */}
      </View>
      {/* 展示测评标题 */}
      <View className={styles.content}>
        {/* 测评介绍 */}
        <View>
          <View className={styles.contentHeader}>
            <View></View>
            <View>
              <Text>测评介绍</Text>
            </View>
          </View>
          <View className="braft-output-content taro_html" dangerouslySetInnerHTML={{ __html: details }}></View>
        </View>
        {/* 指导语 */}
        <View>
          <View className={styles.contentHeader}>
            <View></View>
            <View>
              <Text>指导语</Text>
            </View>
          </View>
          <View className="braft-output-content taro_html" dangerouslySetInnerHTML={{ __html: instruction }}></View>
        </View>
      </View>
      {/* 底部购买收藏按钮 */}
      <View className={styles.footer}>
        {/* 展示收藏按钮 */}
        <View className={isSelected ? styles.checked : styles.unChecked} onClick={changeFavorite}>
          <AtIcon prefixClass="icon" value={isSelected ? 'fabulous-fill' : 'fabulous'} size="26" />
          <Text>{isSelected ? '已收藏' : '收藏'}</Text>
        </View>
        <Button onClick={toPay}>{getDesc()}</Button>
      </View>
      {/* 展示对应的修改弹窗 */}
      {showCheck && <UserDataComfirm isOpened={showCheck} toPayFn={toPay} onClose={() => setShowCheck(false)} />}
    </View>
  );
};

export default AssessmentDetail;
